package com.egao.platform.system.controller;

import com.egao.platform.common.core.BaseController;
import com.egao.platform.common.Constants;
import com.egao.platform.common.core.JsonResult;
import com.egao.platform.system.entity.LoginRecord;
import com.egao.platform.system.entity.Menu;
import com.egao.platform.system.entity.User;
import com.egao.platform.system.service.LoginRecordService;
import com.egao.platform.system.service.MenuService;
import com.egao.platform.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.wf.jwtp.annotation.Ignore;
import org.wf.jwtp.provider.Token;
import org.wf.jwtp.provider.TokenStore;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by wangfan on 2018-12-24 16:10
 */
@Api(tags = "登录认证")
@RestController
@RequestMapping("/api/oauth")
public class OAuthController extends BaseController {
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private LoginRecordService loginRecordService;

    @Ignore
    @ApiOperation("用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "账号", required = true, dataType = "string"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "string")
    })
    @PostMapping("/token")
    public JsonResult login(String username, String password, HttpServletRequest request) {
        User user = userService.getByUsername(username);
        if (user == null) {
            return JsonResult.error("账号不存在");
        }
        if (!userService.comparePsw(user.getPassword(), password)) {
            // 添加登录日志
            loginRecordService.add(user.getUserId(), LoginRecord.TYPE_ERROR, "密码错误", request);
            return JsonResult.error("密码错误");
        }
        JsonResult jsonResult = JsonResult.ok("登录成功");
        // 签发token
        Token token = tokenStore.createNewToken(String.valueOf(user.getUserId()), Constants.TOKEN_EXPIRE_TIME);
        jsonResult.put("access_token", token.getAccessToken());
        jsonResult.put("expire_in", token.getExpireTime());
        jsonResult.put("refresh_token", token.getRefreshToken());
        jsonResult.put("refresh_token_expire_in", token.getRefreshTokenExpireTime());
        jsonResult.put("token_type", "Bearer");
        // 添加登录日志
        loginRecordService.add(user.getUserId(), LoginRecord.TYPE_LOGIN, null, request);
        return jsonResult;
    }

    @Ignore
    @ApiOperation("Token续期")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "refresh_token", value = "refresh_token", required = true, dataType = "string")
    })
    @PutMapping("/token")
    public JsonResult refresh(String refresh_token, HttpServletRequest request) {
        Token token = tokenStore.refreshToken(refresh_token, Constants.TOKEN_EXPIRE_TIME);
        if (token != null) {
            loginRecordService.add(getLoginUserId(request), LoginRecord.TYPE_REFRESH, null, request);
            return JsonResult.ok().put("access_token", token.getAccessToken()).put("expire_time", token.getExpireTime());
        }
        return JsonResult.error();
    }

    @ApiOperation("退出登录")
    @DeleteMapping("/token")
    public JsonResult logout(HttpServletRequest request) {
        Token token = getLoginToken(request);
        tokenStore.removeToken(token.getUserId(), token.getAccessToken());
        loginRecordService.add(getLoginUserId(request), LoginRecord.TYPE_LOGOUT, null, request);
        return JsonResult.ok("已退出登录");
    }

    @ApiOperation("获取登录用户信息")
    @GetMapping("/user")
    public JsonResult userInfo(HttpServletRequest request) {
        return JsonResult.ok().setData(userService.getFullById(getLoginUserId(request)));
    }

    @ApiOperation("获取登录用户菜单")
    @GetMapping("/menu")
    public JsonResult userMenu(HttpServletRequest request) {
        Token token = getLoginToken(request);
        List<Menu> userMenu;
        if (token.getPermissions() == null || token.getPermissions().length == 0) {
            userMenu = menuService.getUserMenu(getLoginUserId(request));
        } else {
            userMenu = menuService.getUserMenu(Arrays.asList(token.getPermissions()));
        }
        return JsonResult.ok().setData(menuService.toMenuTree(userMenu, 0));
    }

}
